/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: QiniuUtil
 * Author:   zmy
 * Date:     2018/7/31 上午8:46
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.ruoyi.common.utils;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zmy
 * @create 2018/7/31
 * @since 1.0.0
 */

import java.io.IOException;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.QiniuConfig;

public class QiniuUtil {
  

  //密钥
  private  final Auth auth;
  private QiniuConfig qiniuConfig;
  public QiniuUtil(){
    qiniuConfig = SpringUtils.getBean(QiniuConfig.class);
    auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
  }
  //普通上传
  public void upload(byte[] file, String fileName) throws IOException{
    //创建上传对象
    UploadManager uploadManager = new UploadManager();
    String token = auth.uploadToken(qiniuConfig.getBucket());
    try {
      //调用put方法上传
      Response res = uploadManager.put(file,fileName,token);

      //打印返回的信息
      System.out.println(res.bodyString());
    } catch (QiniuException e) {
      Response r = e.response;
      // 请求失败时打印的异常的信息
      System.out.println(r.toString());
      try {
        //响应的文本信息
        System.out.println(r.bodyString());
      } catch (QiniuException e1) {
        //ignore
      }
    }
  }

  //普通删除
  public void delete(String key) throws IOException {
    //实例化一个BucketManager对象
    BucketManager bucketManager = new BucketManager(auth);
    key = key.replace("http://pcoasreeo.bkt.clouddn.com/", "").trim();
    try {
      //调用delete方法移动文件
      bucketManager.delete(qiniuConfig.getBucket(), key);

    } catch (QiniuException e) {
      //捕获异常信息
      Response r = e.response;
      System.out.println(r.toString());
    }
  }
}